package com.example.democonfigserver.config;

import com.example.democonfigserver.modules.app.App;
import com.example.democonfigserver.modules.app.AppRepository;
import com.example.democonfigserver.modules.property.Property;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wangbin
 */
@Component
@Slf4j
public class CustomEnvironmentRepository implements EnvironmentRepository {
    @Resource
    private AppRepository appRepository;

    @Override
    public Environment findOne(String application, String profile, String label) {
        Environment environment = new Environment(application, profile, label, null, null);
        if (!application.contains("_") || "app".equals(application)) {
            return environment;
        }

        String[] strings = application.split("_");
        String projectName = strings[0];
        String appName = strings[1];

        List<App> configList = appRepository.findConfiguration(projectName, appName, profile);
        List<Property> propertyList = configList.stream().flatMap(s -> s.getConfigList().stream()).flatMap(s -> s.getPropertyList().stream()).collect(Collectors.toList());
        Map<String, Object> source = new HashMap<>(10);
        environment.add(new PropertySource(application, source));
        for (Property property : propertyList) {
            if (property.getType() == null) {
                source.put(property.getKey(), String.valueOf(property.getValue()));
                continue;
            }
            switch (property.getType()) {
                case INTEGER:
                    source.put(property.getKey(), Integer.valueOf(property.getValue()));
                    break;
                case BOOLEAN:
                    source.put(property.getKey(), Boolean.valueOf(property.getValue()));
                    break;
                case STRING:
                default:
                    source.put(property.getKey(), String.valueOf(property.getValue()));
                    break;
            }
        }
        return environment;
    }
}
